package com.ruoyi.web.controller.system;

import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.*;
import com.ruoyi.system.domain.Device;
import com.ruoyi.system.domain.SysCompanyThingsboard;
import com.ruoyi.system.domain.vo.QueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;

import javax.validation.constraints.NotNull;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;

@Slf4j
@RestController
@RequestMapping("/system/device.v2")
public class DeviceDataController extends BaseController
{
    @Autowired
    private ISysCompanyThingsboardService sysCompanyThingsboardService;

    @Autowired
    IThingsBoardTenantService thingsBoardTenantService;

    @Autowired
    IProductService productService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;
    @Autowired
    private ISysUserService sysUserService;

    @PreAuthorize("@ss.hasPermi('system:device:connectivity')")
    @GetMapping("/{id}/connectivity")
    public AjaxResult connectivity(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        //TODO 验证当前产品是否属于当前用户所建的项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),id);
        }

//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysCompanyThingsboard sysCompanyThingsboard = sysCompanyThingsboardService.selectSysCompanyThingsboardByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        Device device = deviceService.retrieve(queryVo);
        if (device == null) {
            return AjaxResult.error("没有找到指定的产品");
        }
        if (device.getTerminals().size() == 0) {
            return AjaxResult.success(new JSONObject());
        }
        return AjaxResult.success(deviceService.connectivity(device, sysCompanyThingsboard));
    }

    @PreAuthorize("@ss.hasPermi('system:device:latest')")
    @GetMapping("/{id}/time_series/latest")
    public AjaxResult latestTimeSeries(@PathVariable("id") @NotNull(message = "id不能为null") Integer id)
    {
        //TODO 验证当前产品是否属于当前用户所建的项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),id);
        }

//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysCompanyThingsboard sysCompanyThingsboard = sysCompanyThingsboardService.selectSysCompanyThingsboardByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        Device device = deviceService.retrieve(queryVo);
        if (device == null) {
            return AjaxResult.error("没有找到指定的产品");
        }
        if (device.getTerminals().size() == 0) {
            return AjaxResult.success(new JSONObject());
        }
        return AjaxResult.success(deviceService.latestTimeSeries(device, sysCompanyThingsboard));
    }

    @PreAuthorize("@ss.hasPermi('system:device:latest')")
    @GetMapping("/{id}/time_series/meta")
    public AjaxResult timeSeriesMeta(@PathVariable("id") @NotNull(message = "id不能为null") Integer id)
    {
        //TODO 验证当前产品是否属于当前用户所建的项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),id);
        }

//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysCompanyThingsboard sysCompanyThingsboard = sysCompanyThingsboardService.selectSysCompanyThingsboardByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        Device device = deviceService.retrieve(queryVo);
        if (device == null) {
            return AjaxResult.error("没有找到指定的产品");
        }
        if (device.getTerminals().size() == 0) {
            return AjaxResult.success(new JSONObject());
        }
        return AjaxResult.success(deviceService.timeSeriesMeta(device, sysCompanyThingsboard));
    }

    @PreAuthorize("@ss.hasPermi('system:device:history')")
    @GetMapping("/{id}/time_series/history")
    public AjaxResult historicalTimeSeries(
        @PathVariable("id") @NotNull(message = "id不能为null") Integer id,
        @RequestParam(name = "start", required = false) Long start,
        @RequestParam(name = "end", required = false) Long end,
        @RequestParam(name = "identifiers") JSONArray identifiers,
        @RequestParam(name = "aggregation") String aggregation) {
        //TODO 验证当前产品是否属于当前用户所建的项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),id);
        }

//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysCompanyThingsboard sysCompanyThingsboard = sysCompanyThingsboardService.selectSysCompanyThingsboardByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        Device device = deviceService.retrieve(queryVo);
        if (device == null) {
            return AjaxResult.error("没有找到指定的产品");
        }
        if (device.getTerminals().size() == 0) {
            return AjaxResult.success(new JSONArray());
        }
        queryVo.filters.clear();
        if (start == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            start = calendar.getTimeInMillis();
        }
        if (end == null) {
            end = System.currentTimeMillis();
        }
        queryVo.filters.put("start", start);
        queryVo.filters.put("end", end);
        queryVo.filters.put("identifiers", identifiers);
        queryVo.filters.put("aggregation", aggregation);
        return AjaxResult.success(deviceService.historicalTimeSeries(device, queryVo, sysCompanyThingsboard));
    }
}
